package com.zzyl.framework.interceptor;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.net.http.HttpRequest;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Optional;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Autowired
    private HttpServletRequest request;

    public boolean isApp(){
        try {
            return request.getRequestURI().contains("/member");
        } catch (Exception e) {
            return true;
        }
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        // 插入时自动填充字段（示例）
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        if (!isApp()){
            this.strictInsertFill(metaObject, "createBy", String.class,loadUserId() + "");
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 更新时自动填充 updateTime
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
   if (!isApp()){
            this.strictUpdateFill(metaObject, "updateBy", String.class, loadUserId() + "");
        }
    }

    /**
     * 获取当前登录人的ID
     * @return
     */
    public static Long loadUserId(){
        //获取当前登录人的id
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(ObjectUtils.isNotEmpty(loginUser)){
            return loginUser.getUserId();
        }
        return 1L;
    }
}